<!--
//
// message.vue
// hs-admin
//
// Created by 区区电脑 on 2023/05/01.
//
-->
<template>
    <div class="h-message">
        <div class="tabs">
            <!--<el-tabs v-model="requestBody.type" class="demo-tabs" @tab-change="onTypeChange">-->
            <!--    <el-tab-pane :name="1" label="必学资源"></el-tab-pane>-->
            <!--    <el-tab-pane :name="2" label="考试计划"></el-tab-pane>-->
            <!--    <el-tab-pane :name="3" label="准备考试"></el-tab-pane>-->
            <!--</el-tabs>-->
            <!--<b-icon name="bi-arrow-clockwise" class="reload"/>-->
            <div class="tools">
                <span class="button reload" @click="reload(true)"><b-icon class="icon" name="bi-arrow-clockwise" size="16"/>刷新</span>
                <span class="button read-all" @click="readAll"><b-icon class="icon" name="bi-eye" size="16"/>一键已读</span>
                <span class="button remove-all" @click="removeAll"><b-icon class="icon" name="bi-trash3" size="14"/>一键清空</span>
            </div>
        </div>
        <div v-loading="state.isLoading" class="message-list">
            <el-empty v-if="!list || list.length === 0" :image-size="100"/>
            <div v-for="item in list" :key="item.id" :class="{'is-read':item.isRead === 1}" class="cell" @click="onMessageClick(item)">
                <div class="un-read"></div>
                <div class="title">
                    <el-tag v-if="item.typeNum === 5" effect="dark" type="success">已通过</el-tag>
                    <el-tag v-if="item.typeNum === 6" effect="dark" type="danger">未通过</el-tag>
                    {{ item.decription }}
                </div>
                <div class="time">{{ filters.dateFilter(item.createdTime) }}</div>
            </div>
        </div>
        <div class="page-config">
            <vxe-pager
                    v-model:current-page="requestParams.pageIndex"
                    v-model:page-size="requestParams.pageSize"
                    :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Total']"
                    :page-sizes="pageConfig.sizes"
                    :total="pageConfig.total"
                    :pager-count="5"
                    background
                    size="mini"
                    @page-change="onPageChange"/>
        </div>
    </div>
</template>

<script lang="jsx" setup>
import {ref, reactive, computed, onMounted} from "vue";
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import * as api from "./api.js"
import messageAudio from "@/assets/audio/message.mp3"
import {Bell} from "@element-plus/icons-vue"

const props = defineProps({});
const emits = defineEmits();

// 路由
const router = useRouter();
// store
const store = useStore();

// 响应式数据
const state = reactive({
    // 表格数据加载中
    isLoading: false,
})
// 表格数据
const list = computed(() => {
    return (store.getters.globalMessageList || []);
})
// 过滤器
const filters = computed(() => {
    return {
        dateFilter(val) {
            return $dayjs(val).format("YYYY-MM-DD HH:mm")
        }
    }
})

// 请求query参数
const requestParams = reactive({
    orderCol: "createdTime",
    isDesc: true,
    pageIndex: 1,
    pageSize: 10,
});
// 请求body参数
const requestBody = reactive({
    type: null,
})
// 分页配置
const pageConfig = reactive({
    total: 0,
    sizes: [10, 20, 50, 100, 200]
})

// 切换类型
function onTypeChange(val) {
    console.log(val)
    reload(true)
}

// 一键已读
function readAll() {
    api.SetMessageRead().then(({success}) => {
        if (!success) return;
        reload(true)
    })
}

// 一键清空
function removeAll() {
    api.CleanMessageInfo().then(({success}) => {
        if (!success) return;
        reload(true)
    })
}

// 查询列表
async function loadList() {
    const params = {
        ...requestParams
    };
    const body = {
        ...requestBody,
        typeNum: requestBody.type
    };
    state.isLoading = true;
    const {success, data} = await api.GetMessageInfoPageList(params, body);
    state.isLoading = false;
    if (!success) return 0;
    const {items, totalCount} = data;
    store.dispatch("setGlobalMessageList", items)
    pageConfig.total = totalCount;
}

// 分页事件
function onPageChange({type}) {
    if (type === "current") {
        loadList()
    }
    if (type === "size") {
        reload(true)
    }
}

// 刷新
function reload(resetPageIndex) {
    if (resetPageIndex) requestParams.pageIndex = 1;
    loadList()
}

// 点击消息
async function onMessageClick(item) {
    const {success} = await api.UpdateMessageStatus({id: item.id})
    if (!success) return;
    store.dispatch("readMessage", item.id)
    if (item.typeNum === 1) {
        return router.push(`/?page=/My/MySource/Index&titleName=我的学习资源&t=${new Date().getTime()}`)
    }
    if (item.typeNum === 2) {
        return router.push(`/?page=/My/MyPlan/Index&titleName=我的考试计划&t=${new Date().getTime()}`)
    }
    if (item.typeNum === 3) {
        return router.push(`/?page=/My/MyPlan/Index&titleName=我的考试计划&t=${new Date().getTime()}`)
    }
    if (item.typeNum === 4) {
        return router.push(`/?page=/Workflow/Log/Index&titleName=待办审批&t=${new Date().getTime()}`)
    }
    /**
     * 5:审批通过
     * 6:审批不通过
     */
    if (item.typeNum === 5 || item.typeNum === 6) {
        // 通过和不通过要跳转的页面相同
        let path = "";
        switch (item.orderType) {
            case 1:
                path = `/?page=/BaseData/Document/Index&titleName=文本征求意见&t=${new Date().getTime()}`;
                break;
            case 2:
                path = `/`;
                break;
            case 3:
                path = `/`;
                break;
            case 11:
                path = `/?page=/MaterialManage/Orders/Index&titleName=物资单据&t=${new Date().getTime()}`;
                break;
            case 12:
                path = `/?page=/MaterialManage/Orders/Index&titleName=物资单据&t=${new Date().getTime()}`;
                break;
            case 13:
                path = `/?page=/MaterialManage/Orders/Index&titleName=物资单据&t=${new Date().getTime()}`;
                break;
            case 14:
                path = `/?page=/MaterialManage/Orders/Index&titleName=物资单据&t=${new Date().getTime()}`;
                break;
            case 15:
                path = `/?page=/MaterialManage/Orders/Index&titleName=物资单据&t=${new Date().getTime()}`;
                break;
            case 16:
                path = `/?page=/MaterialManage/Orders/Index&titleName=物资单据&t=${new Date().getTime()}`;
                break;
            case 51:
                path = `/?page=/Project/ProjectInfo/Index&titleName=项目管理&t=${new Date().getTime()}`;
                break;
            case 81:
                path = `/?page=/LuZhengManage/RoadEngineering/Index&titleName=涉路工程&t=${new Date().getTime()}`;
                break;
            case 82:
                path = `/?page=/LuZhengManage/LuZhengEvent/Index&titleName=路政事件&t=${new Date().getTime()}`;
                break;
            case 83:
                path = `/?page=/RoadCare/YangHuEvent/Index&titleName=养护事件&t=${new Date().getTime()}`;
                break;
            default:
                path = `/`
                break;
        }
        if (path === "/") return
        return router.push(path)
    }
    if (item.typeNum === 7) {
        return router.push(`/?page=/Workflow/WorkLog/Index&titleName=待办工作&t=${new Date().getTime()}`)
    }
    if (item.typeNum === 8) {
        return router.push(`/?page=/Safe/InspectionPlan/Index&titleName=安全检查计划&t=${new Date().getTime()}`)
    }
    if (item.typeNum === 9) {
        return router.push(`/?page=/ReportManage/Report/Index&titleName=报表数据&t=${new Date().getTime()}`)
    }
}


// 播放提示音
function playAudio() {
    const audio = new Audio(messageAudio);
    audio.play()
}

// 注册 signalr 接收实时消息
function registerSignalrMessage() {
    window.$signalr.off("ReceiveMessage")
    window.$signalr.on("ReceiveMessage", (data) => {
        playAudio()
        let title = ""
        if (data.typeNum === 1) {
            title = "必学资源提醒"
        }
        if (data.typeNum === 2) {
            title = "考试计划提醒"
        }
        if (data.typeNum === 3) {
            title = "准备考试提醒"
        }
        if (data.typeNum === 4) {
            title = "您有新的待审批任务"
        }
        if (data.typeNum === 5) {
            title = "您提交的审批已通过"
        }
        if (data.typeNum === 6) {
            title = "您提交的审批未通过"
        }
        if (data.typeNum === 7) {
            title = "您有新的待办任务"
        }
        if (data.typeNum === 8) {
            title = "您有新的安全检查计划待确认"
        }
        if (data.typeNum === 9) {
            title = "您有新的报表填报任务"
        }
        window.$hmessage_onMessageClick = () => {
            customNotification?.close()
            onMessageClick(data)
        }
        const message = `${data.decription} <span onclick="window.$hmessage_onMessageClick()" style="color: var(--el-color-primary);cursor: pointer;padding: 4px 10px;">点击查看</span>`
        const customNotification = window.$notification.custom(title, message, <el-icon size="12" style="color: #67C23A"><Bell/></el-icon>)
        //store.dispatch("pushGlobalMessage", data)
        reload(true)
        console.primary("接收到实时消息", data)
    })
}

onMounted(() => {
    loadList()
    registerSignalrMessage();
})
</script>

<style lang="scss" scoped>
.h-message {
    width: 460px;

    .tabs {
        height: 40px;
        width: 100%;
        padding: 0 10px;
        box-sizing: border-box;
        position: relative;
        border-bottom: 1px solid #e8e8e8;

        .tools {
            position: absolute;
            top: 0;
            right: 12px;
            z-index: 10;
            cursor: pointer;
            color: var(--el-color-primary);
            font-weight: bold;
            height: 40px;
            display: flex;
            flex-direction: row;
            justify-content: flex-end;
            align-items: center;

            .button {
                margin-left: 14px;
                display: flex;
                flex-direction: row;
                justify-content: flex-end;
                align-items: center;

                .icon {
                    margin-right: 4px;
                }

                &:active {
                    opacity: 0.8;
                }
            }

            .remove-all {
                color: var(--el-color-danger);
            }
        }


    }

    //  通知列表
    .message-list {
        width: 100%;
        min-height: 400px;
        box-sizing: border-box;

        .cell {
            width: 100%;
            box-sizing: border-box;
            padding: 10px;
            position: relative;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: flex-start;
            cursor: pointer;

            .title {
                width: calc(100% - 140px);
                padding-left: 14px;
                font-size: 14px;
                color: #333;
            }

            .time {
                width: 110px;
                font-size: 12px;
                color: gray;
                text-align: right;
            }

            .un-read {
                position: absolute;
                top: 14px;
                left: 10px;
                width: 8px;
                height: 8px;
                background-color: var(--el-color-danger);
                border-radius: 10px;
                z-index: 1;
            }


            &::after {
                content: " ";
                position: absolute;
                left: 10px;
                right: 10px;
                bottom: 0;
                background-color: rgba(0, 0, 0, 0.1);
                height: 1px;
            }

            &:hover {
                background-color: var(--el-color-primary-light-8);
                color: var(--el-menu-active-color);

                .title {
                    color: var(--el-color-primary);
                }
            }
        }

        .is-read {
            .un-read {
                display: none;
            }

            .title {
                opacity: 0.7;
            }
        }
    }

    .page-config {
        padding: 8px;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
    }
}
</style>
